from flask import jsonify

#响应工具类
#前端请求后端接口，后端接口的响应格式定义
#

class APIResponse:
    def __init__(self, code, message, data=None):
        self.code = code
        self.message = message
        self.data = data

    def to_dict(self):
        response = {
            "code": self.code,
            "message": self.message
        }
        if self.data is not None:
            response["data"] = self.data
        return response

    @classmethod
    def ok(cls, data=None):
        return cls(code=0, message="success", data=data).to_dict()

    @classmethod
    def error(cls, code, message):
        return cls(code=code, message=message).to_dict()


# 示例用法
if __name__ == "__main__":
    # 创建一个成功的响应
    success_response = APIResponse.ok(data={"user_id": 1, "username": "john_doe"})
    print(success_response.to_dict())

    # 创建一个失败的响应
    error_response = APIResponse.error(code=-1, message="server fail")
    print(error_response.to_dict())

